/**
 * @author 李楠君
 */
/**
 * @author 李楠君
 * 短信群发
 */
package com.safe.ocs.services;

import java.util.List;
import net.sf.json.JSONArray;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.safe.ocs.beans.OMsgPageBean;
import com.safe.ocs.beans.OutputSMS;
import com.safe.ocs.beans.Person;
import com.safe.ocs.utils.HibernateUtil;

public class SendMsg {

	/**
	 * 
	 * @param receiver  收信人号码
	 * @param name      收信人姓名
	 * @return          查询结果
	 */
	public String findPerson(String receiver , String name) {
		String result="";
		StringBuffer hqlWhere = new StringBuffer(" where 1=1");
		if(receiver!=null&&!"".equals(receiver)){
			hqlWhere.append(" and remark=:telNo");
		}
		if(name!=null&&!"".equals(name)){
			hqlWhere.append(" and person_name=:name");
		}
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		try{
			String findHql = "select new Person(person_id, dept_id, card_no, person_no,person_name, person_type, cert_name,cert_code, duty, title, nationality, sex, birthday, is_marry, nativeplace, address, residence, onwork_date, offwork_date,  is_del, remark) from Person"+hqlWhere.toString();
			Query query = session.createQuery(findHql);
			if(receiver!=null&&!"".equals(receiver)){
				query.setParameter("telNo", receiver);
			}
			if(name!=null&&!"".equals(name)){
				query.setParameter("name", name);
			}
			List personList = query.list();
			result = JSONArray.fromObject(personList).toString();
			tr.commit();
		}catch(Exception ex){
			ex.printStackTrace();
			tr.rollback();
		}finally{
			session.close();
		}	
		return result;
	}

	
	/**
	 * 
	 * @param telNos 收信人号码  
	 * @param content  短信内容
	 * @return 发送结果 true表示成功 false表示失败
	 */
	public boolean sendMessage(String[] telNos,String content){
		Session session = HibernateUtil.getSession();
		Transaction tr = session.beginTransaction();
		try{
			for(int i=0;i<telNos.length;i++){
				OutputSMS omsg = new OutputSMS();
				omsg.setTelNo(telNos[i]);
				omsg.setMsg(content);
				omsg.setSendedStaut(false);
			    session.save(omsg);
		    }		
			tr.commit();
		    return true;
		}catch(Exception ex){
			tr.rollback();
			return false;
		}finally{
			session.close();
		}		
	}
}
